package net.zdreamer.geracomium.ui.more;

import android.annotation.TargetApi;
import android.app.ActionBar.LayoutParams;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.geracomium.R;

import net.zdreamer.geracomium.application.BaseApplication;
import net.zdreamer.geracomium.myviews.CustomProgressDialog;
import net.zdreamer.geracomium.ui.BaseActivity;
import net.zdreamer.geracomium.utils.PersonalinfoUtils.IdcardUtils;
import net.zdreamer.geracomium.utils.file.SharePreferencesUtil;
import net.zdreamer.geracomium.utils.httputils.PersonalCenterService;
import net.zdreamer.geracomium.utils.tools_utils.URLTools;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.DateFormat;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;

public class PersonalInformationActivity extends BaseActivity implements
        OnClickListener {
    private LinearLayout personal_name, personal_sex, personal_age,
            personal_identity_card, personal_birth_date,
            personal__native_place, personal_address, personal_live_address,
            personal_interest,sexback;

    private PopupWindow pop_sex;
    private TextView no_choose, sex_choose, uerinfor_name,
            id_card, tv_bith_data, info_age, infor_intrest, infor_bed,
            info_native, info_address, info_live_address, tv_elderinfo, tv_commit;
    private View sex_view;
    private RelativeLayout man_choose, woman_choose;
    private ImageView image_man, image_woman, tv_oldman;

private Dialog loadingDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int getContentView() {
        return R.layout.activity_personal_information;
    }

    @Override
    protected void init() {
        personal_name = (LinearLayout) findViewById(R.id.personal_name);
        personal_sex = (LinearLayout) findViewById(R.id.personal_sex);
        personal_age = (LinearLayout) findViewById(R.id.personal_age);
        personal_identity_card = (LinearLayout) findViewById(R.id.personal_identity_card);
        personal_birth_date = (LinearLayout) findViewById(R.id.personal_birth_date);
        personal__native_place = (LinearLayout) findViewById(R.id.personal__native_place);
        personal_address = (LinearLayout) findViewById(R.id.personal_address);
        personal_live_address = (LinearLayout) findViewById(R.id.personal_live_address);
        personal_interest = (LinearLayout) findViewById(R.id.personal_interest);

        tv_bith_data = (TextView) findViewById(R.id.tv_bith_data);
        id_card = (TextView) findViewById(R.id.id_card);
        info_age = (TextView) findViewById(R.id.info_age);
        sex_choose = (TextView) findViewById(R.id.sex_choose);
        uerinfor_name = (TextView) findViewById(R.id.uerinfor_name);
        infor_intrest = (TextView) findViewById(R.id.infor_intrest);
        info_native = (TextView) findViewById(R.id.info_native);
        info_address = (TextView) findViewById(R.id.info_address);
        info_live_address = (TextView) findViewById(R.id.info_live_address);
        tv_elderinfo = (TextView) findViewById(R.id.tv_elderinfo);
        tv_commit = (TextView) findViewById(R.id.tv_commit);

        loadingDialog = CustomProgressDialog.createLoadingDialog(this,"正在提交……");
    }

    @Override
    protected void initViews() {
        initTitle("个人资料", R.drawable.selector_title_back,
                R.drawable.selector_guardianindo, true, true);

        setSexPopuwindow();

    }

    @Override
    protected void initListener() {
        findViewById(R.id.back).setOnClickListener(this);
        findViewById(R.id.share).setOnClickListener(this);
        personal_name.setOnClickListener(this);
        personal_sex.setOnClickListener(this);
        personal_age.setOnClickListener(this);
        personal_identity_card.setOnClickListener(this);
        personal_birth_date.setOnClickListener(this);
        personal__native_place.setOnClickListener(this);
        personal_address.setOnClickListener(this);
        personal_live_address.setOnClickListener(this);
        personal_interest.setOnClickListener(this);

        tv_elderinfo.setOnClickListener(this);
        tv_commit.setOnClickListener(this);


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.share:
                Intent guar = new Intent(PersonalInformationActivity.this, GuardianActivity.class);
                startActivity(guar);

                break;
            case R.id.personal_name:
                Intent editname = new Intent(PersonalInformationActivity.this,
                        PersonalInformationEditActivity.class);
                editname.putExtra("info", "姓名");
                startActivityForResult(editname, 0);
                break;
            case R.id.personal_sex:
                pop_sex.showAtLocation(v, Gravity.CENTER, 0, getStatusBarHeight());
                break;
            case R.id.personal_identity_card:
                Intent editIDcard = new Intent(PersonalInformationActivity.this,
                        PersonalInformationEditActivity.class);
                editIDcard.putExtra("info", "身份证");
                startActivityForResult(editIDcard, 0);
                break;
            case R.id.personal__native_place:
                Intent choose_native = new Intent(
                        PersonalInformationActivity.this,
                        ChooseAdressActivity.class);
                choose_native.putExtra("info", "籍贯");
                choose_native.putExtra("source", "personalinfo");
                startActivity(choose_native);
                break;
            case R.id.personal_address:
                Intent choose_address = new Intent(
                        PersonalInformationActivity.this,
                        ChooseAdressActivity.class);
                choose_address.putExtra("info", "户口地址");
                choose_address.putExtra("source", "personalinfo");
                startActivity(choose_address);
                break;
            case R.id.personal_live_address:
                Intent choose_liveaddress = new Intent(
                        PersonalInformationActivity.this,
                        ChooseAdressActivity.class);
                choose_liveaddress.putExtra("info", "居住地址");
                choose_liveaddress.putExtra("source", "personalinfo");
                startActivity(choose_liveaddress);
                break;
            case R.id.personal_interest:
                Intent editinterest = new Intent(
                        PersonalInformationActivity.this,
                        PersonalInformationEditActivity.class);
                editinterest.putExtra("info", "老人兴趣");
                startActivityForResult(editinterest, 0);
                break;
            case R.id.no_choose:
                pop_sex.dismiss();
                break;
            case R.id.man_choose:
                image_man.setVisibility(View.VISIBLE);
                image_woman.setVisibility(View.GONE);
                sex_choose.setText("男");
                pop_sex.dismiss();
                break;
            case R.id.woman_choose:
                image_man.setVisibility(View.GONE);
                image_woman.setVisibility(View.VISIBLE);
                sex_choose.setText("女");
                pop_sex.dismiss();
                break;
            case R.id.tv_elderinfo:
                Intent elder = new Intent(PersonalInformationActivity.this, ElderInfofmationActivity.class);
                startActivity(elder);
                break;
            case R.id.tv_commit:
                if (!isEmpty())
                    Toast.makeText(this, "请补全信息", Toast.LENGTH_SHORT).show();
                else SubmitInfo();
                //    SubmitInfo();
                break;
            case R.id.sexback:
                pop_sex.dismiss();
                break;
            default:
                break;
        }

    }

    public boolean isEmpty() {
        if (tv_bith_data.getText().equals("") || sex_choose.getText().equals("") || id_card.getText().equals(""))
            return false;
        else return true;
    }

    /**
     * 请求数据
     */
    @TargetApi(Build.VERSION_CODES.KITKAT)
    private void SubmitInfo() {
        DateFormat format = DateFormat.getDateInstance();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("guardianId", BaseApplication.get().getUserId());

        map.put("status","Registered");
        map.put("name", uerinfor_name.getText().toString());
        map.put("sex", sex());
        map.put("age", info_age.getText().toString());
        map.put("idNo", id_card.getText().toString());
        map.put("residenceAddress", info_address.getText().toString());
        try {
                map.put("birthday", format.parse(tv_bith_data.getText().toString()));
        } catch (ParseException e) {
            e.printStackTrace();
          //  System.out.println(e.getMessage());
        }
        map.put("nativePlace", info_native.getText().toString());
        map.put("registeredAddress", info_live_address.getText().toString());
        map.put("hobby", infor_intrest.getText().toString());


        PersonalCenterService.RegistPost(map, URLTools.OldmanUrl, handler);
        loadingDialog.show();
        SharePreferencesUtil.Writer(this, "OldInfos", map);
       // System.out.println(map);
    }


    public String sex() {
        if (sex_choose.getText().equals("男")) {
            return "Male";
        } else {
            return "Female";
        }
    }

    public JSONObject balance() {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("balance", 1000);
            return jsonObject;
        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }
    }


    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.arg1) {
                case 201:
                  //  System.out.println("提交成功");
                    loadingDialog.dismiss();
                    Toast.makeText(PersonalInformationActivity.this, "提交成功", Toast.LENGTH_SHORT).show();
                    break;
                case 401:
                    loadingDialog.dismiss();
                    Toast.makeText(PersonalInformationActivity.this, "提交失败,请重新提交", Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
        }
    };

    // 回调方法,返回输入的信息
    @Override
    protected void onActivityResult(int requestCode, int resultCode,
                                    Intent intent) {
     //   System.out.println(intent);
        if (intent != null) {
            String change01;

            if (intent.getStringExtra("姓名") != null) {
                change01 = intent.getStringExtra("姓名");
                uerinfor_name.setText(change01);
            } else if (intent.getStringExtra("身份证") != null) {
                change01 = intent.getStringExtra("身份证");
                id_card.setText(change01);

            } else if (intent.getStringExtra("老人兴趣") != null) {
                change01 = intent.getStringExtra("老人兴趣");
                infor_intrest.setText(change01);
            } else if (intent.getStringExtra("老人床位") != null) {
                change01 = intent.getStringExtra("老人床位");
                infor_bed.setText(change01);
            }

        }
        getBrithDate();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if (EditAdressActivity.edit_index != null) {

            if (EditAdressActivity.edit_index.equals("籍贯")) {
                info_native.setText(EditAdressActivity.back_address);
            } else if (EditAdressActivity.edit_index.equals("户口地址")) {
                info_address.setText(EditAdressActivity.back_address);
            } else if (EditAdressActivity.edit_index.equals("居住地址")) {
                info_live_address.setText(EditAdressActivity.back_address);
            }
        }
    }

    /**
     * 获取生日年龄
     */
    private void getBrithDate() {
        String brith = id_card.getText().toString().trim();
        if (brith != "") {
            tv_bith_data.setText(IdcardUtils.getbrith(brith));
            info_age.setText(String.valueOf(IdcardUtils.getAge(brith)));
        }
    }


    /**
     * 选择性别
     */
    private void setSexPopuwindow() {
        // TODO
        LayoutInflater inflater = LayoutInflater.from(this);
        sex_view = inflater.inflate(R.layout.pop_sex, null);
        pop_sex = new PopupWindow(sex_view, LayoutParams.FILL_PARENT,
                LayoutParams.FILL_PARENT);
        pop_sex.setBackgroundDrawable(new ColorDrawable(0x77000000));
        pop_sex.setOutsideTouchable(true);
        pop_sex.setFocusable(true);

        sexback=(LinearLayout)sex_view.findViewById(R.id.sexback);
        no_choose = (TextView) sex_view.findViewById(R.id.no_choose);
        man_choose = (RelativeLayout) sex_view.findViewById(R.id.man_choose);
        woman_choose = (RelativeLayout) sex_view
                .findViewById(R.id.woman_choose);
        image_man = (ImageView) sex_view.findViewById(R.id.image_man);
        image_woman = (ImageView) sex_view.findViewById(R.id.image_woman);

        sexback.setOnClickListener(this);
        man_choose.setOnClickListener(this);
        woman_choose.setOnClickListener(this);
        no_choose.setOnClickListener(this);
    }

    /**
     * popwindow覆盖全屏
     *
     * @return
     */
    public int getStatusBarHeight() {
        int result = 0;
        int resourceId = getResources().getIdentifier("status_bar_height",
                "dimen", "android");
        if (resourceId > 0) {
            result = getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

}
